# -*- coding: utf-8 -*-
# createTime: 2018/9/6 10:58
from kombu import BrokerConnection, Exchange, Queue
from kombu.mixins import ConsumerMixin
from kombu import Consumer

import logging, sys

logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logger = logging.getLogger(__name__)


EXCHANGE_NAME = "nova"
ROUTING_KEY = "notifications.info"
# QUEUE_NAME = "nova_dump_queue"
BROKER_URI = "amqp://guest:guest@10.99.100.21:5672//"


class NotificationsDump(ConsumerMixin):
    channel2 = None

    def __init__(self, connection):
        self.connection = connection
        return

    def get_consumers(self, consumer, default_channel):
        self.channel2 = default_channel.connection.channel()
        exchange1 = Exchange('nova', type="topic", durable=False)
        queue1 = Queue(exchange=exchange1, routing_key=ROUTING_KEY, durable=False, auto_delete=True, no_ack=True)
        exchange2 = Exchange('neutron', type="topic", durable=False)
        queue2 = Queue(exchange=exchange2, routing_key=ROUTING_KEY, durable=False, auto_delete=True, no_ack=True)
        return [Consumer(default_channel, queue1,
                         callbacks=[self.on_message],
                         accept=['json']),
                Consumer(self.channel2, queue2,
                         callbacks=[self.on_special_message],
                         accept=['json'])]

        # exchange = Exchange(EXCHANGE_NAME, type="topic", durable=False)
        # queue = Queue(exchange=exchange, routing_key=ROUTING_KEY, durable=False, auto_delete=True, no_ack=True)
        # return [consumer(queue, callbacks=[self.on_message], accept=['json'])]

    def on_special_message(self, body, message):
        logger.info('Channel2-Body: %r' % body)
        logger.info('=======================')

    def on_message(self, body, message):
        logger.info('Body: %r' % body)
        logger.info('---------------')


if __name__ == "__main__":
    logger.info("Connecting to broker {}".format(BROKER_URI))
    print("Connecting to broker {}".format(BROKER_URI))
    with BrokerConnection(BROKER_URI) as connection:
        NotificationsDump(connection).run()
